import {
  CSys,
  EventsRes,
  MathTool,
  MouseInfo,
  SceneSetup,
  SketchFrame,
} from '@amcax/base';
import { ctx2 } from '@app-cad/module';
import { Vector2tuple, Vector3 } from 'three-legacy';
import { wsApi } from '@app-cad/server/wsApi';
import { DimObject } from './type';
import { sketchEventCenter } from '@app-cad/environments/nextcad/events/SketchEventCenter';
import { DimAngleTool } from '../dimension/DimAngleTool';
export class DimDrag {
  private sceneSetup: SceneSetup;
  private planeNormal: Vector3;
  private planeOrigin: Vector3;
  private frame: number[][];
  private faceCSys: CSys;
  public sketchFrame;
  points: Vector2tuple[];
  type: string;
  static instance: DimDrag;
  private sketchId: string;
  startPoint: Vector3;
  constructor() {
    this.init();
  }
  pickeDim: DimObject;
  setPickeDim(pickeDim, mouse?: MouseInfo) {
    this.pickeDim = pickeDim;
    this.points = pickeDim?.userData?.points;
    this.type = pickeDim?.userData?.type;
    if (mouse) {
      this.startPoint = this.getPointByMouse(mouse);
    }
  }
  static getInstance(): DimDrag {
    if (!this.instance) {
      this.instance = new DimDrag();
    }
    return this.instance;
  }
  static removeInstance() {
    if (this.instance) {
      this.instance = null;
    }
  }
  init() {
    const { frame, sketchId } = sketchEventCenter().getSketchInfo();
    this.frame = frame;
    this.sketchId = sketchId;
    this.sceneSetup = ctx2.viewer.sceneSetup;
    this.faceCSys = MathTool.createCsysFromPlacement(this.frame);
    this.planeNormal = this.faceCSys.getNormalVc3();
    this.planeOrigin = this.faceCSys.getOriginVc3();
    this.sketchFrame = new SketchFrame(this.frame);
  }
  // 鼠标移动
  onMouseMove = (e: EventsRes) => {
    if (!this.pickeDim) {
      return;
    }
    const point = this.getPointByMouse(e.mouse);
    if (!this.pickeDim.dimLabel.isActive) {
      // this.pickeDim?.offset({  });
      this.pickeDim?.offset(point.clone().sub(this.startPoint));
      this.startPoint = point;
    }
    ctx2.viewer.requestRender();
  };
  // 根据鼠标位置获取点位置（世界坐标）
  getPointByMouse(mouse: MouseInfo) {
    const mousePoint = this.sceneSetup?.mouseOnPlane(
      mouse.x,
      mouse.y,
      this.planeNormal,
      this.planeOrigin,
    );
    return this.sketchFrame.toLocal(mousePoint);
  }
  // 鼠标按下
  onMouseUp = async () => {
    if (!this.pickeDim || !this.pickeDim.userData.id) {
      return;
    }
    let points = this.points;
    if (this.pickeDim.userData.type === 5) {
      if (points.length === 2) {
        points[0] = this.pickeDim.getPosLv()[0];
      } else {
        points = [
          ...this.pickeDim.getPosLv(),
          ...(this.pickeDim as DimAngleTool).getDimArcInfo(),
        ];
      }
    } else {
      points = this.pickeDim.getPosLv();
    }
    await wsApi.updateDimension(this.sketchId, {
      annotation: this.pickeDim.userData.id,
      points,
    });
  };
}
export const dimDrag = () => {
  return DimDrag.getInstance();
};
